module BreathLed (
        input clk,
        input rst_n,

        output reg led
    );

    // 预计2s一次暗<->亮,总脉冲数
    parameter MaxCount =16'd1000;
    // 50MHz时钟,2秒,划分为1000个脉冲
    // 脉冲内的Hz变化的最小单元值,每个脉冲都需要有这么多的Hz数 进行变化,最小变化单元是2us
    parameter PulseHzStep = 32'd50_000_000*32'd2 / 32'd1000 / 32'd1000;

    // 当前是递增还是递减,1递增,0递减
    reg direction;
    // 2s计数器,2ms的数据达到1000后递增
    reg [31:0] t2sCounter;
    // 2ms计数器,2us的数值达到1000后递增
    reg [31:0] t2msCounter;
    // 2us,最小变化单元的Hz计数器
    reg [31:0] t2usCounter;

    // 递增递减
    always @(posedge clk or negedge rst_n) begin
        if(!rst_n)
            direction <= 1'b1;
        else
            // 计数达到MaxCount个2ms,改变方向
            direction <= (t2sCounter == MaxCount-32'd1
                          && t2msCounter == (MaxCount-32'd1)
                          && t2usCounter== (PulseHzStep-32'd1)) ? ~direction : direction;
    end

    // 2s计数器
    always @(posedge clk or negedge rst_n) begin
        if(!rst_n)
            t2sCounter <= 32'd0;
        else if(t2sCounter == MaxCount-32'd1
                && t2msCounter == (MaxCount-32'd1)
                && t2usCounter== (PulseHzStep-32'd1))
            t2sCounter <= 32'd0;
        else if (t2msCounter == (MaxCount-32'd1) && t2usCounter== (PulseHzStep-32'd1))
            t2sCounter <= t2sCounter + 32'd1;
        else
            t2sCounter <= t2sCounter;
    end

    // 2ms计数器
    always @(posedge clk or negedge rst_n) begin
        if(!rst_n)
            t2msCounter<= 32'd0;
        else if(t2msCounter == (MaxCount-32'd1) && t2usCounter== (PulseHzStep-32'd1))
            t2msCounter <= 32'd0;
        else if (t2usCounter== PulseHzStep-32'd1)
            t2msCounter<= t2msCounter + 32'd1;
        else
            t2msCounter<= t2msCounter;
    end


    // 2us,最小变化单元的Hz计数器
    always @(posedge clk or negedge rst_n) begin
        if(!rst_n)
            t2usCounter <= 32'd0;
        else if (t2usCounter == PulseHzStep-32'd1)
            t2usCounter <= 32'd0;
        else
            t2usCounter <= t2usCounter + 32'd1;
    end

    // LED控制
    always @(posedge clk or negedge rst_n) begin
        if(!rst_n)
            led <= 1'b0;
        else begin
            if(direction==1'b1 && t2msCounter <=t2sCounter || direction==1'b0 && t2msCounter >=t2sCounter)
                led <= 1'b1;
            else
                led <= 1'b0;
        end
    end

endmodule
